package de.slothsoft.commons.swing;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.List;

import javax.swing.TransferHandler;

public abstract class AbstractFilesDropTransferHandler extends TransferHandler {

	private static final long serialVersionUID = 7L;

	private static final DataFlavor FLAVOR = DataFlavor.javaFileListFlavor;

	private boolean multipleFilesAllowed;

	@Override
	public boolean canImport(TransferSupport support) {
		for (DataFlavor flavor : support.getDataFlavors()) {
			if (flavor.equals(FLAVOR)) {
				return true;
			}
		}
		return false;
	}

	@Override
	@SuppressWarnings("unchecked")
	public boolean importData(TransferSupport support) {
		try {
			Transferable transfareable = support.getTransferable();
			List<File> list = (List<File>) transfareable
					.getTransferData(FLAVOR);
			return importFiles(list);
		} catch (Exception e) {

			return false;
		}
	}

	protected boolean importFiles(List<File> list) {
		if (list.size() > 0) {
			for (File file : list) {
				importFile(file);
				if (this.multipleFilesAllowed) {
					break;
				}
			}
			return true;
		}
		return false;
	}

	protected abstract boolean importFile(File file);

	public boolean isMultipleFilesAllowed() {
		return this.multipleFilesAllowed;
	}

	public void setMultipleFilesAllowed(boolean multipleFilesAllowed) {
		this.multipleFilesAllowed = multipleFilesAllowed;
	}
}
